﻿using System;
using System.Threading.Tasks;
using CoreLib.ConfigOptions;
using Microsoft.Extensions.Options;
using RestSharp;

namespace Ids.UserServices.Implements
{
    public class ApproveServiceLoginServer : IUserService
    {
        private readonly IOptions<ApproveServiceOptions> _options;

        public ApproveServiceLoginServer(
            IOptions<ApproveServiceOptions> options
            )
        {
            _options = options ?? throw new ArgumentNullException(nameof(options));
        }

        public async Task<UserObject> Login(string userName, string password, string mac)
        {
            var restclient = new RestClient(_options.Value.Host);

            var request = new RestRequest("MobileLogon")
                .AddJsonBody(new
                {
                    aUserCode = userName,
                    aPwd = password,
                    aMAC = mac
                });

            var response = await restclient
                .PostAsync<ResponseModel>(request);

            if (response.IsSuccessful && response.Data.rt.RE.IsLoginSuccess)
            {
                return new UserObject { Token = response.Data.rt.RE.KEY, UserCode = userName };
            }

            throw new ArgumentException("登录失败");
        }

        public class ResponseModel
        {
            public string Msg { get; set; }

            public int Status_code { get; set; }

            public DataObject Data { get; set; }

            internal bool IsSuccessful => Status_code == 1;
        }
        public class DataObject
        {
            public RTObject rt { get; set; }
        }

        public class RTObject
        {
            public REObject RE { get; set; }
        }

        public class REObject
        {
            public bool IsLoginSuccess => "0".Equals(RC);

            public string RC { get; set; }

            public string KEY { get; set; }
        }
    }
}
